# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : zsj.py
# @Time     : 2024/4/21 22:16
# @Author   : Robot-Zsj
"""
description:

i:
4 4
2 1 0 3
0 1 2 1
0 3 0 0
0 0 0 0

o:
2
"""
m, n = map(int,input().split())
matrix = [list(map(int, input().split())) for _ in range(m)]

class UnionFindSet:
    def __init__(self,n):
        self.fa = [i for i in range(n)]

    def find(self,x):
        if x != self.fa[x]:
            self.fa[x] = self.find(self.fa[x])
            return self.fa[x]
        return x

    def union(self, x, y):
        x_fa = self.find(x)
        y_fa = self.find(y)
        if x_fa != y_fa:
            self.fa[y_fa] = x_fa

def getResult():
    rows = len(matrix)
    cols = len(matrix[0])

    ufs = UnionFindSet(rows*cols)

    huawei = []
    restaurants = []
    offsets = ((-1,0),(0,-1),(1,0),(0,1))

    for i in range(rows):
        for j in range(cols):
            if matrix[i][j]!=1:
                pos = i*cols +j
                if matrix[i][j] ==2:
                    # 收集小华，小为的位置
                    huawei.append(pos)
                elif matrix[i][j] == 3:
                    # 收集餐厅的位置
                    restaurants.append(pos)
                for offset in offsets:
                    newI = i + offset[0]
                    newJ = j + offset[1]

                    if 0 <= newI < rows and 0 <= newJ < cols and matrix[newI][newJ] !=1:
                        # 如果（i，j）和（newI，newJ）位置都是非1，则合并
                        ufs.union(pos, newI*cols+newJ)
    # 小华所在连通分量的根
    hua_fa = ufs.find(huawei[0])
    # 小为所在连通分量的根
    wei_fa = ufs.find(huawei[1])

    # 如果小华和小为不在同一连通分量，则二人无法去往相同餐厅
    if hua_fa != wei_fa:
        return 0

    # 找出和小华，小为在同一个连通分量里面的餐厅
    ans = 0
    for r in restaurants:
        if ufs.find(r) == hua_fa:
            ans+=1
    return ans

print(getResult())